package com.lsh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lsh.common.HealthException;
import com.lsh.dao.SetmealDao;
import com.lsh.entity.PageResult;
import com.lsh.entity.QueryPageBean;
import com.lsh.pojo.Setmeal;
import com.lsh.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Override
    @Transactional
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        //先添加套餐
        setmealDao.add(setmeal);
        //添加套餐与检查组关系
        if (checkgroupIds.length>0 && checkgroupIds != null){
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealCheckgroup(setmeal.getId(),checkgroupId);
            }
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //插件分页
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<Setmeal> setmealList = setmealDao.findPage(queryPageBean);
        PageInfo<Setmeal> setmealPageInfo = new PageInfo<>(setmealList);
        return new PageResult(setmealPageInfo.getTotal(),setmealPageInfo.getList());
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> findCheckgroupIdsBySetmealId(Integer id) {
        return setmealDao.findCheckgroupIdsBySetmealId(id);
    }
    @Transactional
    @Override
    public void update(Integer[] checkgroupIds, Setmeal setmeal) {
        //先更新套餐
        setmealDao.update(setmeal);
        //删除旧关系
        setmealDao.deleteCheckgroupIdsBySetmealId(setmeal.getId());
        //添加新关系
        if(checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealCheckgroup(setmeal.getId(),checkgroupId);
            }
        }
    }
    @Transactional
    @Override
    public void deleteById(Integer id) {
        //先查询套餐是否被订单使用
        Long count = setmealDao.findOrderIdBySetmealId(id);
        if (count > 0){
            throw new HealthException("此套餐被订单使用，无法删除");
        }
        //先删除套餐与检查组关系
        setmealDao.deleteCheckgroupIdsBySetmealId(id);
        //删除套餐
        setmealDao.deleteById(id);
    }

    @Override
    public List<String> findAllImgName() {
        return setmealDao.findAllImgName();
    }
}
